package com.cw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cw.entity.Category;

import com.cw.entity.Dish;
import com.cw.entity.Setmeal;
import com.cw.handler.CustomException;
import com.cw.mapper.CategoryMapper;
import com.cw.service.CategoryService;
import com.cw.service.DishService;
import com.cw.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Slf4j
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService  dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void delete(Long id) {
        //1.获取数据

        //2.添加查询条件
        // select count(*) from dish where category_id = ?
        QueryWrapper<Dish> dishQueryWrapper = new QueryWrapper<>();
        dishQueryWrapper.select("count(*) AS count");//投影
        dishQueryWrapper.eq("category_id",id);
        //执行查询
        Map<String, Object> map = dishService.getMap(dishQueryWrapper);
        Long count = (Long) map.get("count");

        //3.判断是否有菜品
        if (count>0){
            log.info("此分类有菜品，不能删除！！");
            throw new CustomException("此分类有菜品，不能删除！！");

        }

        //4.检查套餐是否在分类中
        QueryWrapper<Setmeal> setmealQueryWrapper = new QueryWrapper<>();
        // select count(*) from dish where category_id = ?
        setmealQueryWrapper.select("count(*) AS count");
        setmealQueryWrapper.eq("category_id",id);

        //执行查询
        Map<String, Object> setmealServiceMap = setmealService.getMap(setmealQueryWrapper);
        Long setmealCount = (Long) setmealServiceMap.get("count");

        //5.判断套餐是否在分类中
        if (setmealCount>0){
            log.info("此分类有套餐，不能删除！！");
            throw new CustomException("此分类有套餐，不能删除！！");
        }


        //6.如果都没有就删除
        super.removeById(id);

    }
}
